package com.feilong.edgeAI.speech;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Log;


import java.io.File;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by【仿脑科技】
 *
 * @Author: potato
 * @CreateDate: 2023/11/14 14:25
 */
public class RecordeHelper {
    private static final String TAG = "RecordeHelper";
    public static boolean isRecording;

    private AudioRecord audioRecord;
    private static int SAMPLE_RATE_IN_HZ = 16000;
    private int sampleRateInHz;
    private int audioFormat;
    private int bufferSize;

    @SuppressLint("MissingPermission")
    public void createAudioRecord() {
        Log.e(TAG, "startRecord: createAudioRecord();");
        sampleRateInHz = 16000;
        int channelConfig = AudioFormat.CHANNEL_IN_MONO;
        audioFormat = AudioFormat.ENCODING_PCM_16BIT;
        bufferSize = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
//        if(null==audioRecord){
            audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRateInHz, channelConfig, audioFormat, bufferSize);
//        }
        audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE_IN_HZ,
                AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
        if(audioRecord.getState() == AudioRecord.STATE_UNINITIALIZED){
            Log.d(TAG, "createAudioRecord: 11111");
            audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE_IN_HZ,
                    AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
            if(audioRecord.getState() == AudioRecord.STATE_UNINITIALIZED){
                Log.d(TAG, "createAudioRecord: 22222");
                audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE_IN_HZ / 2,
                        AudioFormat.CHANNEL_CONFIGURATION_DEFAULT, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
            }
        }


    }

    private StringBuilder iatRes = new StringBuilder();
    private static final Executor threadExecutor = new ThreadPoolExecutor(1, 1, 30,
            TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(10));
    public void startRecord() {
        Log.d(TAG, "startRecord: >>>>>>>>>>>>>>>>");
        if(isRecording==true)return;
//        if(null==audioRecord){
//            createAudioRecord();
//        }
        Log.d(TAG, "startRecord: audioRecord="+audioRecord);
        if(null==audioRecord||audioRecord.getRecordingState()== AudioRecord.STATE_UNINITIALIZED){
            createAudioRecord();

        }

        Log.d(TAG, "startRecord: audioRecord.getRecordingState()222="+audioRecord.getRecordingState());
        Log.e(TAG, "startRecord: isRecording>>="+isRecording);

//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//
//            }
//        }).start();
        try{
            audioRecord.startRecording();
            isRecording = true;
            threadExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    if(null!=recordListener){
                        recordListener.onStart();
                    }
                    while (isRecording) {
                        if(null==audioRecord){
                            isRecording = false;
                            break;
                        }
                        byte[] buffer = new byte[bufferSize];
                        int readStatus = audioRecord.read(buffer, 0, bufferSize);
//                    Log.d(TAG, "run: "+readStatus+"  thread="+Thread.currentThread().getName()+"  isRecording="+isRecording);
                        if(null!=recordListener){
                            recordListener.onRecording(buffer);
                        }
                        long sum = 0;
                        for (int i = 0; i < readStatus; i++) {
                            sum += Math.abs(buffer[i]);
                        }
                        if (readStatus > 0) {
                            int amplitude = (int) (sum / readStatus);
                            int volume = (int) (20 * Math.log10(amplitude));
//                        Log.d(TAG, "run: volume="+volume+"  byte[] buffer= "+buffer.length);
                            if(null!=recordListener){
                                recordListener.onVolume(volume);
                            }
                            // 处理音量大小
                        }
                    }
                }
            });
        }catch (Exception e){
//            if(null!=audioRecord){
//                audioRecord.release();
//                audioRecord = null;
//            }
//            startRecord();
            Log.d(TAG, "startRecord:Exception >>>>>>>>>>>>>>>>");
            e.printStackTrace();
        }
    }
    public void stopRecord(){
        isRecording = false;
        if(null==audioRecord)return;
        audioRecord.stop();
        audioRecord.release();
        audioRecord = null;
        Log.e(TAG, "stopRecord: isRecording>>="+isRecording);
        if(null!=recordListener){
            recordListener.onStop();
        }
    }
  /*  public void createAudioRecord() {
        RecordManager recordManager = RecordManager.getInstance();
        RecordConfig config = recordManager.getRecordConfig();
        config.setRecordDir("");
        config.setSampleRate(16000);
        config.setEncodingConfig(AudioFormat.ENCODING_PCM_16BIT);
        recordManager.changeRecordConfig(config);
        recordManager.setRecordStateListener(new RecordStateListener() {
            @Override
            public void onStateChange(RecordHelper.RecordState state) {
                Log.d(TAG, "onStateChange: state="+state.name());
            }

            @Override
            public void onError(String error) {
                Log.d(TAG, "onError: "+error);
            }
        });
        recordManager.setRecordDataListener(new RecordDataListener() {
            @Override
            public void onData(byte[] data) {
                if(null!=recordListener){
                    recordListener.onRecording(data);
                }
            }
        });
        RecordManager.getInstance().setRecordSoundSizeListener(new RecordSoundSizeListener() {
            @Override
            public void onSoundSize(int volume) {
                if(null!=recordListener){
                    recordListener.onVolume(volume);
                }
            }
        });
//        RecordManager.getInstance().setSource(RecordConfig.SOURCE_SYSTEM);
    }*/
//    public void startRecord(){
//        RecordManager.getInstance().start();
////        recorder.startRecording();
//    }
//    public void stopRecord(){
//        RecordManager.getInstance().stop();
////        recorder.stopRecording();
//    }
//    public void resumeRecord(){
//        RecordManager.getInstance().resume();
////        recorder.resumeRecording();
//    }
//    public void pasueRecord(){
//        RecordManager.getInstance().pause();
////        recorder.pauseRecording();
//    }
   /* private Recorder recorder;
    public Recorder getRecorder(Context context) {
        // 请确保当前app有 RECORD_AUDIO 权限
        AudioRecordConfig recordConfig = new AudioRecordConfig();
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
        return MsRecorder.wav(
//                new File(AbilityInit.IFLYTEK_ROOT+"/test.wav"),
                null,
                recordConfig,
                // new AudioRecordConfig(MediaRecorder.AudioSource.MIC, AudioFormat.ENCODING_PCM_16BIT, AudioFormat.CHANNEL_IN_MONO, 44100),
                // 普通录音模式
                new PullTransport.Default()
                        .setOnAudioChunkPulledListener(new PullTransport.OnAudioChunkPulledListener() {
                            @Override
                            public void onAudioChunkPulled(AudioChunk audioChunk) {
                                if(null!=recordListener){
                                    recordListener.onRecording(audioChunk.toBytes());
                                    recordListener.onVolume((int) (audioChunk.maxAmplitude()));

                                }
//                                Log.d("数据监听", "最大值 : ${audioChunk.maxAmplitude()} "+audioChunk.maxAmplitude());
//                                animateVoice((float) (audioChunk.maxAmplitude() / 200.0));
                            }
                        })
        );
    }
    public void createAudioRecord(Context context) {
        recorder = getRecorder(context);
    }*/
    private RecordListener recordListener;

    public void setRecordListener(RecordListener recordListener) {
        this.recordListener = recordListener;
    }

    public interface RecordListener{
        void onStart();
        void onStop();
        void onVolume(int volume);
        void onRecording(byte[] buffer);
    }
}
